// ************************************************************
// Copyright © 2022
// File Name: main.go
// Author:
// Email:
// Created: 2022-02-05 11:12:30 (CST)
// Last Update:
//          By:
// Description:
// ************************************************************
package main

import (
	"goim/packet"
	"log"
	"net"
	"sync"

	"github.com/lucasepe/codename"
)

func startNewConn() {
	conn, err := net.Dial("tcp", ":9999")
	if err != nil {
		log.Println("Dial error: ", err)
		return
	}

	defer conn.Close()
	log.Println("dial ok")

	rng, err := codename.DefaultRNG()
	if err != nil {
		panic(err)
	}

	var wg sync.WaitGroup

	message := codename.Generate(rng, 10)
	sendPkt := packet.NewIMPackage()
	sendPkt.Body = []byte(message)
	sendPkt.Operation = packet.Message
	sendPkt.ProtocalVer = 0x4d
	sendPkt.SequenceID = 0x23
	sendPkt.PackageLen = uint32(20 + len(sendPkt.Body))
	log.Println("Send package len: ", sendPkt.PackageLen)

	sendPkt.Print()
	err = sendPkt.Encode(conn)
	if err != nil {
		log.Println("Encode error: ", err)
		return
	}
	log.Println("Send ok")

	wg.Add(1)
	go func() {
		defer wg.Done()
		recvPkt := packet.NewIMPackage()
		err := recvPkt.Decode(conn)
		if err != nil {
			log.Println("Recv error: ", err)
			return
		}
		recvPkt.Print()
	}()
	wg.Wait()

}

func main() {
	startNewConn()
}
